
package com.dyzx.hbb.security.handler;

import com.alibaba.fastjson.JSON;
import com.dyzx.hbb.common.base.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        
        System.out.println("\n=== Authentication Failed ===");
        System.out.println("Request URI: " + request.getRequestURI());
        System.out.println("Request Method: " + request.getMethod());
        System.out.println("Exception message: " + authException.getMessage());
        System.out.println("Exception type: " + authException.getClass().getName());
        
        // 获取当前的认证信息
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            System.out.println("Current Authentication: " + auth);
            System.out.println("Is Authenticated: " + auth.isAuthenticated());
            System.out.println("Principal: " + auth.getPrincipal());
            System.out.println("Authorities: " + auth.getAuthorities());
        } else {
            System.out.println("No Authentication found in SecurityContext");
        }
        
        String errorMessage;
        if (request.getAttribute("jwt_error") != null) {
            errorMessage = request.getAttribute("jwt_error").toString();
        } else if (authException.getMessage() != null) {
            errorMessage = authException.getMessage();
        } else {
            errorMessage = "认证失败，请重新登录";
        }
        
        // 检查是否是JWT相关的错误
        if (authException.getCause() != null && authException.getCause().getMessage() != null) {
            String causeMessage = authException.getCause().getMessage();
            if (causeMessage.contains("JWT")) {
                errorMessage = "Token已过期或无效，请重新登录";
            }
        }
        
        System.out.println("Returning error message: " + errorMessage);
        
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");
        
        Result<?> result = Result.error(401, errorMessage);
        response.getWriter().print(JSON.toJSONString(result));
    }
}